#!/usr/bin/env python
"""
初始化 MySQL 数据库并可选执行 Django 迁移。

用法示例：
  .\.venv\Scripts\python.exe scripts\init_db.py --migrate
  .\.venv\Scripts\python.exe scripts\init_db.py --host 127.0.0.1 --port 3306 --user root --password 123456 --db Cloud --migrate

环境变量（均为可选，优先于命令行默认值）：
  DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME

说明：
  - 默认参数与 settings.py 保持一致：host=localhost, port=3306, user=root, password=123456, db=Cloud
  - 仅负责创建数据库（utf8mb4），表结构由 Django 迁移生成（--migrate）
"""
import os
import sys
import argparse
import subprocess

import mysql.connector
from mysql.connector import Error


def create_database(host: str, port: int, user: str, password: str, db_name: str,
                    charset: str = "utf8mb4", collate: str = "utf8mb4_general_ci") -> None:
    conn = None
    try:
        conn = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            port=port,
        )
        cur = conn.cursor()
        cur.execute(f"CREATE DATABASE IF NOT EXISTS `{db_name}` DEFAULT CHARACTER SET {charset} DEFAULT COLLATE {collate}")
        conn.commit()
        print(f"数据库 `{db_name}` 已创建或已存在（字符集: {charset}, 排序: {collate}）")
    except Error as e:
        print(f"创建数据库失败: {e}")
        raise
    finally:
        if conn:
            conn.close()


def verify_connection(host: str, port: int, user: str, password: str, db_name: str) -> None:
    conn = None
    try:
        conn = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            port=port,
            database=db_name,
            charset='utf8mb4'
        )
        if conn.is_connected():
            cursor = conn.cursor()
            cursor.execute("SELECT DATABASE();")
            record = cursor.fetchone()
            print(f"验证连接成功，当前数据库: {record[0]}")
    except Error as e:
        print(f"验证连接失败: {e}")
        raise
    finally:
        if conn:
            conn.close()


def run_migrate(base_dir: str) -> None:
    # 优先使用项目本地虚拟环境 python
    venv_python = os.path.join(base_dir, ".venv", "Scripts", "python.exe")
    python_exec = venv_python if os.path.exists(venv_python) else sys.executable
    print(f"使用 Python 解释器: {python_exec}")
    cmd = [python_exec, "manage.py", "migrate"]
    print("执行迁移: ", " ".join(cmd))
    proc = subprocess.run(cmd, cwd=base_dir, check=True)
    if proc.returncode == 0:
        print("Django 迁移完成")



def parse_args():
    parser = argparse.ArgumentParser(description="初始化 MySQL 数据库并可选执行 Django 迁移")
    # 从环境变量读取默认值
    env_host = os.environ.get("DB_HOST", "localhost")
    env_port = int(os.environ.get("DB_PORT", "3306"))
    env_user = os.environ.get("DB_USER", "root")
    env_password = os.environ.get("DB_PASSWORD", "123456")
    env_name = os.environ.get("DB_NAME", "Cloud")

    parser.add_argument("--host", default=env_host, help="MySQL 主机")
    parser.add_argument("--port", type=int, default=env_port, help="MySQL 端口")
    parser.add_argument("--user", default=env_user, help="MySQL 用户")
    parser.add_argument("--password", default=env_password, help="MySQL 密码")
    parser.add_argument("--db", default=env_name, help="数据库名称")
    parser.add_argument("--charset", default="utf8mb4", help="数据库字符集")
    parser.add_argument("--collate", default="utf8mb4_general_ci", help="数据库排序规则")
    parser.add_argument("--migrate", action="store_true", help="创建数据库后执行 Django 迁移")
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    # 1) 创建数据库
    create_database(
        host=args.host,
        port=args.port,
        user=args.user,
        password=args.password,
        db_name=args.db,
        charset=args.charset,
        collate=args.collate,
    )

    # 2) 验证连接
    verify_connection(
        host=args.host,
        port=args.port,
        user=args.user,
        password=args.password,
        db_name=args.db,
    )

    # 3) 可选执行迁移
    if args.migrate:
        run_migrate(base_dir)
